﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;

namespace Gmis.VideoConvert
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        static string ffmpeg = AppDomain.CurrentDomain.BaseDirectory + @"\ffmpeg\ffmpeg.exe";
        public VideoEncoder newcoder = new VideoEncoder();

        public MainWindow()
        {
            InitializeComponent();
            newcoder.Progress +=new VideoEncoder.ProgressEventHandler(newcoder_Progress);
            newcoder.Status += new VideoEncoder.StatusEventHandler(newcoder_Status);
        }

        #region
        public void newcoder_Progress(int prog, string tl)
        {
            this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background,  new Action(() =>  pb.Value = prog));           
            //Application.DoEvents();
        }

        private void newcoder_Status(string status)
        {
            this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, new Action(() => txtMessage.Text = status));           
        }

        private void Converter(string FromName, string ExportName)
        {
            newcoder.OverWrite = false;
            newcoder.SourceFile = (string)(FromName);
            newcoder.Format = "flv";
            newcoder.AudioCodec = "libmp3lame";// newcoder.AudioCodec_mp3;
            newcoder.AudioBitrate = "128k";
            newcoder.Video_Codec = "libx264";//newcoder.Vcodec_h264;
            newcoder.Threads = "0";
            newcoder.OverWrite = true;
            //  newcoder.ConstantRateFactor = 22
            newcoder.RateControl = newcoder.RateControl_ABR;
            newcoder.VideoBitrate = "1000k";

            newcoder.Libx264_Preset_pass1 = newcoder.libx264_fast;

            newcoder.OutputPath = ExportName;
            newcoder.AnalyzeFile();

            newcoder.Encode();            
        }


        #endregion
        ///**/
        ///// 视频(avi,mov等等格式)转换为flv格式视频
        ///// </summary>
        ///// <param name="FromName">被转换的视频文件</param>
        ///// <param name="ExportName">转换flv后的文件名</param>
        ///// <param name="WidthAndHeight">视频大小的尺寸</param>
        ///// <returns></returns>
        //public string VideoConvertFlv(string FromName, string ExportName, string WidthAndHeight)
        //{           
        //    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(ffmpeg);
        //    startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
        //    //startInfo.Arguments = " -i " + Server.MapPath(FromName) + " -ab 56 -ar 22050 -b 500 -r 15 -s "+WidthAndHeight+" "+Server.MapPath  (ExportName);
        //    startInfo.Arguments = " -i " + FromName + " -ab 56 -ar 22050 -b 500 -r 15 -s " + WidthAndHeight + " " + ExportName;
        //    try
        //    {
        //        System.Diagnostics.Process.Start(startInfo);
        //        return ExportName;
        //    }
        //    catch (Exception err)
        //    {
        //        return err.Message;
        //    }
        //}

        ///**/
        ///// <summary>
        ///// 从视频画面中截取一帧画面为图片
        ///// </summary>
        ///// <param name="VideoName">视频文件pic/guiyu.mov</param>
        ///// <param name="WidthAndHeight">图片的尺寸如:240*180</param>
        ///// <param name="CutTimeFrame">开始截取的时间如:"1"</param>
        ///// <returns></returns>
        //public string GetPicFromVideo(string VideoName, string WidthAndHeight, string CutTimeFrame)
        //{          
        //    //string PicName = Server.MapPath(Guid.NewGuid().ToString().Replace("-", "") + ".jpg");
        //    //System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(ffmpeg);
        //    //startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
        //    //startInfo.Arguments = " -i " + Server.MapPath(VideoName) + " -y -f image2 -ss " + CutTimeFrame + " -t 0.001 -s " + WidthAndHeight + " " + PicName;
        //    //try
        //    //{
        //    //    System.Diagnostics.Process.Start(startInfo);
        //    //    return PicName;
        //    //}
        //    //catch (Exception err)
        //    //{
        //    //    return err.Message;
        //    //}

        //    return "";
        //}

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //string FFmpegArguments = @" -i D:\离歌.wmv -ab 56 -ar 22050 -b 500 -r 15 -s 320x240 D:\离歌.flv ";
            ////ProcessStartInfo info = new ProcessStartInfo("D:/ffmpeg/ffmpeg", FFmpegArguments);
            ////Process.Start(info);

            //Process p = new Process(); //Process類有一個StartInfo屬性，這個是ProcessStartInfo類，包括了一些屬性和方法，下面我們用到了他的幾個屬性：
            //p.StartInfo.FileName = "D:/ffmpeg/ffmpeg.exe";//設定程序名
            //p.StartInfo.Arguments = FFmpegArguments;    //設定程式執行參數
            //p.StartInfo.UseShellExecute = false;        //關閉Shell的使用
            //p.StartInfo.RedirectStandardInput = true;   //重定向標準輸入
            //p.StartInfo.RedirectStandardOutput = true;  //重定向標準輸出
            //p.StartInfo.RedirectStandardError = true;   //重定向錯誤輸出
            //p.StartInfo.CreateNoWindow = true;          //設置不顯示窗口
            //p.Start();                                  //啟動
            ////p.StandardInput.WriteLine(FFmpegArguments);//也可以用這種方式輸入要執行的命令
            ////p.StandardInput.WriteLine("exit");         //不過要記得加上Exit要不然下一行程式執行的時候會當機
            //Application.StartupPath;
            if (string.IsNullOrEmpty(txtInput.Text.Trim()))
            {
                MessageBox.Show("请选择视频文件!");
                return;
            }

            if (string.IsNullOrEmpty(txtOutput.Text.Trim()))
            {
                MessageBox.Show("请选择视频转换后的保存路径!");
                return;
            }
            param.IsEnabled = false;
            string fileName = System.IO.Path.GetFileName(txtInput.Text.Trim());
            string fileExt = System.IO.Path.GetExtension(txtInput.Text.Trim());
            fileName = fileName.Replace(fileExt, ".flv");
            //VideoConvertFlv(txtInput.Text.Trim(), txtOutput.Text.Trim() + "\\"  + fileName, "320x240");
            Converter(txtInput.Text.Trim(), txtOutput.Text.Trim());
            param.IsEnabled = true;
        }

        private void btnSelectIn_Click(object sender, RoutedEventArgs e)
        {            
            // Create OpenFileDialog
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            // Set filter for file extension and default file extension 
            dlg.DefaultExt = ".rmvb";//wma,rm,avi,mod
            dlg.Filter = "视频文件|*.rmvb;*.wmv;*.rm;*.avi;*.mod";
            // Display OpenFileDialog by calling ShowDialog method 
            Nullable<bool> result = dlg.ShowDialog();
            // Get the selected file name and display in a TextBox 
            if (result == true)
            {
                // Open document 
                string filename = dlg.FileName;              
                txtInput.Text = filename;
            }
        }

        private void btnSelectOut_Click(object sender, RoutedEventArgs e)
        {
            //FolderBrowserDialog  
           System.Windows.Forms.FolderBrowserDialog fbd = new System.Windows.Forms.FolderBrowserDialog();  
           fbd.ShowDialog();  
           if (fbd.SelectedPath != string.Empty)  
               txtOutput.Text = fbd.SelectedPath; 

        }
    }
}
